/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: ProcessXZXPX
 * Author:   ThinkPad
 * Date:     2020/6/24 17:05
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.jt.www.queue.process;

import com.jt.www.enums.issue.IssueEnum;
import com.jt.www.enums.issue.PolicyInterfaceEnum;
import com.jt.www.model.issue.entity.IssuePolicyLogEntity;
import com.jt.www.model.issue.entity.IssueRecordEntity;
import com.jt.www.util.DateUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

/**
 * @author xq.wu
 * @Description 徐州学平险（徐州学平意外险/徐州监护人责任险）
 * @create 2020/6/24
 * @since 1.0.0
 */
@Service
public class ProcessXZXPX extends ElecPolicyProcess implements InitializingBean {

    public static final Logger log = LoggerFactory.getLogger(ProcessXZXPX.class);


    @Override
    public void afterPropertiesSet() throws Exception {
        IssuePolicyIfCodeFactory.register(PolicyInterfaceEnum.CODE_18.getIfCode(), this);
    }

    @Override
    public Boolean process(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 解析险种 19PR941489
        //String proCode = "19PR941489";
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);
        // 108001 代表徐州学平意外险， 107001 代表徐州监护人责任险
        String transactionCode = reqPacket.element("head").element("transactionCode").getStringValue();

        log.debug("系统时间：{}, [徐州学平险]下载电子保单 投保单号：{},保单号：{},产品险种编码：{},徐州学平意外险(108001)/徐州监护人责任险(107001)：{}", currentTime, tbNo, policyNo, proCode, transactionCode);
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        if (judgingStorage(tbNo)) {
            return true;
        }
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);

        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");

        //000000：成功  其余：失败
        String status = respPacket.element("head").element("responseCompleteMessageStatus").element("messageStatusCode").getStringValue();
        if ("000000".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);

        //流水号
        String seqNo = Long.toString(Math.abs(new Random().nextLong()));
        //调用数据交换平台时入参ifCode
        String company = "";

        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("request");
        Element head = info.addElement("head");
        //转换编码
        //transactionCode = 108001(代表徐州学平意外险) 调用数据交换平台下载电子保单时传输编码为：108005
        //transactionCode = 107001(代表徐州学平意外险) 调用数据交换平台下载电子保单时传输编码为：107003
        if ("108001".equals(transactionCode)) {
            head.addElement("partnerCode");
            head.addElement("messageId").addText(seqNo);//流水号
            head.addElement("transactionCode").addText("108005");// 意外险标示 108005:代表徐州学平意外险
            head.addElement("transactionEffectiveDate").addText(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            head.addElement("user");
            head.addElement("password");
            Element body = info.addElement("body");
            Element epolicyInfoReprint = body.addElement("epolicyInfoReprint");
            epolicyInfoReprint.addElement("policyNo").addText(policyNo);
            epolicyInfoReprint.addElement("messageFlag");
            epolicyInfoReprint.addElement("emailFlag");
            epolicyInfoReprint.addElement("returnPDFFlag");

            company = "20190729002";
        } else if ("107001".equals(transactionCode)) {
            head.addElement("partnerCode");
            head.addElement("transactionCode").addText("107003");// 意外险标示 107003:代表徐州监护人责任险
            head.addElement("messageId").addText(seqNo);//流水号
            head.addElement("transactionEffectiveDate").addText(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            head.addElement("user");
            head.addElement("password");
            Element body = info.addElement("body");
            Element entity = body.addElement("entity");
            entity.addElement("plcNo").addText(policyNo);
            entity.addElement("elcMsgFlag");
            entity.addElement("elcMobile");
            entity.addElement("elcEmlFlag");
            entity.addElement("elcEmail");
            entity.addElement("returnPDF");

            company = "20190729003";
        }

        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("徐州学平险的投保单号是: {}, 保单下载参数：{}", tbNo, info.asXML());
            // 请求下载保单，成功更新
            ResponseEntity<String> responseEntity = dexClient.text("edu", company, "1.0", seqNo, info.asXML());
            String ebody = responseEntity.getBody();
            log.info("徐州学平险的投保单号是: {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), ebody);

            Document resultDoc = DocumentHelper.createDocument();
            resultDoc = DocumentHelper.parseText(ebody);
            Element ebodyElement = resultDoc.getRootElement();
            Element data = ebodyElement.element("data");
            consumeStatus = "2";
            if (data == null) {
                log.error("徐州学平险请求下载电子保单失败");
                consumeStatus = "3";
            }
            String fileId = data.getStringValue();

            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info("徐州学平险的投保单号是  下载消息 fileId：{}", fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}